#!/usr/bin/env python
#http://python.zirael.org/e-gtk-uimanager1.html
# ensure that PyGTK 2.0 is loaded - not an older version
import pygtk
pygtk.require('2.0')
# import the GTK module
import gtk

import os
import sys
import subprocess
import shlex
import ConfigParser
import random
import pango #for fonts
import dialogs

try:
  import vte
except:
  print >> sys.stderr, "You need to have python-libvte installed."
  sys.exit(1)

class MyGUI:

  #ui_file = open('adore-gui.ui', 'r')
  #ui = ui_file.read()

  def __init__( self, title,argv):
    self.argv=argv or "/scr/adore -i"
    self.set = ConfigParser.ConfigParser()
    self.window = gtk.Window()
    self.title = title
    self.window.set_title( title)
    #self.window.set_size_request( 800, 600)
    try:
      self.window.set_icon_from_file(ADOREGUIFOLDER+"/adore-doris-gui-icon-256px.png")
    except Exception, e:
      print e.message
      pass
    self.window.connect( "destroy", self.destroy)
    self.create_interior()
    self.window.show_all()

  def create_interior( self):
    import ui_config
    self.mainbox = gtk.VBox()
    self.window.add( self.mainbox)
    # eventbox
    #http://www.eurion.net/python-snippets/snippet/Get%20Selection.html
    # The eventbox allows us to read the selection in the vte-terminal
    self.eventbox = gtk.EventBox()
    self.eventbox.connect("selection_received", self.selection_received)
    self.mainbox.pack_start(self.eventbox)
    self.eventbox.show()
          
    # create action group
    self.actiongroup = gtk.ActionGroup('MyActionGroup')
    self.actiongroup.add_actions(ui_config.menuActions(self))
    self.menuCommands=ui_config.menuCommands;
    # the uimanager
    self.uimanager = gtk.UIManager()
    accelgroup = self.uimanager.get_accel_group()
    self.window.add_accel_group( accelgroup)

    self.uimanager.insert_action_group( self.actiongroup, 0)
    #self.uimanager.add_ui_from_string(self.ui)
    self.uimanager.add_ui_from_file(ADOREFOLDER + '/gui/agooey.ui')
    # menu bar
    self.menu_bar = self.uimanager.get_widget( "/MenuBar")
    self.mainbox.pack_start( self.menu_bar, expand=False, fill=False)
    self.menu_bar.show()
    # right justify the about menu
#    self.uimanager.get_widget('/MenuBar/AboutMenu').set_right_justified( True)
    # label for answer
#    self.answer_label = gtk.Label( "Hello menus")
#    self.mainbox.pack_start( self.answer_label, padding=10)
#    self.answer_label.show()
    # vte term
    self.v = vte.Terminal()
    self.v.connect("child-exited", lambda term: gtk.main_quit())
    self.v.connect('button-press-event', self.do_button_press)    
    self.v.connect_object('selection-changed', self.get_stringtarget, self.eventbox)
    self.v.set_word_chars("-0-9A-Za-z,./<>?;':\"[]{}\\|_+=!@#$%^&*()`~");
    self.v.set_scrollback_lines(-1); #Set to infinite scrollback.
    #self.argv="adore -i -u /home/bosmanoglu/tmp/test/settings.set"
    #self.v.fork_command("sh", ["/bin/bash", "-c", "adore -i" ])
    #self.v.fork_command("sh", ["/bin/bash", "-c", "adore -i -u /home/bosmanoglu/tmp/test/settings.set"])
    #THIS WORKS but creates spawns 3 shells instead of two#self.vPid=self.v.fork_command("sh", ["/bin/bash", "-c", self.argv])
    self.setFile="/tmp/adore"+str(random.randint(0,10000))+".set"
    self.argv=self.argv + str('-g %s ' %self.setFile);
    cmd=self.argv.split(" ");
    #print cmd
    self.vPid=self.v.fork_command(cmd[0], cmd);#USAGE:fork_command(args[0], args, None, os.getcwd())
    #print self.vPid
    #self.v.fork_command("sh", shlex.split(self.argv))
    #self.mainbox.pack_start(self.v)
    self.eventbox.add(self.v)
    
    # show the box
    self.mainbox.show()

  def main(self):
    gtk.main()

  def readSet(self): #readSettings
    self.set.read(self.setFile)

  def runcmd(self, cmd):
    self.v.feed_child(cmd+'\n');

  def destroy( self, w):
    gtk.main_quit()

  def do_button_press(self, terminal, event):
    if event.button == 3:
        self.create_popup(event)
        return True
    else:
        return False
    
  def capture_text(self,text,text2,text3,text4):
    #read current window with:
    #    print self.v.get_text(self.capture_text);
    return True

  def get_stringtarget(self, widget):
    # And request the "STRING" target for the primary selection
    ret = widget.selection_convert("PRIMARY", "STRING")
    return

  # Signal handler called when the selections owner returns the data
  def selection_received(self, widget, selection_data, data):
    # Make sure we got the data in the expected form    
    if str(selection_data.type) == "STRING":
      self.selectionText=selection_data.get_text();
    return False

  def create_popup(self, event):
    menu = gtk.Menu()

    copy_item = gtk.ImageMenuItem('_Copy')
    copy_icon = gtk.image_new_from_stock(gtk.STOCK_COPY,
                                         gtk.ICON_SIZE_MENU)
    copy_item.set_image(copy_icon)

    paste_item = gtk.ImageMenuItem('_Paste')
    paste_icon = gtk.image_new_from_stock(gtk.STOCK_PASTE,
                                         gtk.ICON_SIZE_MENU)
    paste_item.set_image(paste_icon)
    
    open_item = gtk.ImageMenuItem('_Open')

    clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
    if not clipboard.wait_is_text_available():
        paste_item.set_sensitive(False)

    if not self.v.get_has_selection():
        copy_item.set_sensitive(False)
        open_item.set_sensitive(False)
        
    #menu.append(gtk.SeparatorMenuItem())
    menu.append(copy_item)
    menu.append(paste_item)
    menu.append(open_item)
    #menu.append(gtk.SeparatorMenuItem())
    #menu.append(gtk.SeparatorMenuItem())
    #menu.append(im_menu)

    copy_item.connect('activate', lambda x: self.v.copy_clipboard())
    paste_item.connect('activate', lambda x: self.v.paste_clipboard())
    open_item.connect('activate', lambda x: self.runcmd('xdg-open ' + self.selectionText + ' &') )
    menu.show_all()
    menu.popup(None, None, None, 3, event.time)

  def set_font(self):
    # font for terminal
    response, newfont=dialogs.font()
    font = pango.FontDescription(newfont)
    self.v.set_font_full(font, True)
    self.v.set_size_request(80,24); # this allows us to make the window really small if needed.
    
if __name__ == "__main__":
  ADOREGUIFOLDER=os.path.split(os.path.realpath(sys.argv[0]))[0]
  ADOREFOLDER=os.path.split(ADOREGUIFOLDER)[0]
  #print ADOREFOLDER
  argv=ADOREFOLDER + "/scr/adore -i "
  if len(sys.argv[1:]) >0:
    argv+= " ".join(sys.argv[1:]);
  #  #print argv
  #argv=sys.argv[1:];
  m = MyGUI("ADORE GUI",argv)  
  m.main()

  
